<template>
    <div class="star-box">
      <div
        class="star-item"
        :class="{ active: item === 1 }"
        @click="changeLevel(index)"
        v-for="(item, index) in starList"
        :key="index"
      ></div>
    </div>
  </template>
  <script setup>
  import { ref,watch } from "vue";
  
  const props = defineProps({
    level: {
      type: Number,
      default: 0,
    },
    canEdit: {
      type: Boolean,
      default: false,
    },
  });
  
  const starList = ref([]);
  const emits = defineEmits(["change"]);
  
  // for (let i = 0; i < 5; i++) {
  //   starList.value.push(i < props.level ? 1 : 0);
  // }
  
  // watch level->starList
  watch(
    () => props.level,
    (newVal) => {
      for (let i = 0; i < 5; i++) {
        starList.value[i] = i < newVal ? 1 : 0;
      }
    },
    {
      immediate: true,
    }
  );
  
  const changeLevel = (index) => {
    if (!props.canEdit) {
      return;
    }
    if(starList.value[index] === 1 && starList.value[index + 1] === 0) {
      starList.value[index] = 0;
      return;
    } else if(index === 4 && starList.value[index] === 1){
      starList.value[index] = 0;
      return;
    }
    for (let i = 0; i <= index; i++) {
      starList.value[i] = 1;
    }
    for (let i = index + 1; i < 5; i++) {
      starList.value[i] = 0;
    }
    emits("change", index + 1);
  };
  </script>
  <style scoped>
  .star-box {
    display: flex;
    align-items: center;
    column-gap: 15px;
  }
  .star-item {
    width: 31px;
    height: 31px;
    background-size: 100% 100%;
    background-image: url("../assets/image/star-grey.png");
    cursor: pointer;
  }
  .star-item.active {
    background-image: url("../assets/image/star.png");
  }
  </style>
  